<template>
	<view class="addEditForm">
		<view class="data-form bgfff">
			<view class="data-form-item flex-ac">
				<text class="data-form-label f30">供应商</text>
				<!-- <view class="data-form-input">
					<cpdd-select v-model="dataForm.supplierId" :disabled="optionDisabled" :list="selectList"
						keyname="name" valname="val"></cpdd-select>
				</view> -->
				<view class="data-form-input" @click="openSelect">
					<input type="text" :disabled="optionDisabled" v-model="dataForm.supplierName"
						:placeholder="optionDisabled?'-':'请选择供应商'" placeholder-class="plStyle" />
				</view>
			</view>
			<view class="data-form-item flex-ac">
				<text class="data-form-label f30">采购类型</text>
				<view class="data-form-input">
					<cpdd-select v-model="dataForm.type" @change="typeChange" :disabled="optionDisabled"
						:list="typeList" keyname="name" valname="val"></cpdd-select>
				</view>
			</view>
			<view class="data-form-item flex-ac">
				<text class="data-form-label f30">社会信用代码</text>
				<view class="data-form-input">
					<input type="text" :disabled="optionDisabled" v-model="dataForm.creditCode"
						:placeholder="optionDisabled?'-':'请输入关键词'" placeholder-class="plStyle" />
				</view>
			</view>
			<view class="data-form-item flex-ac">
				<text class="data-form-label f30">购物凭证文件</text>
				<view class="data-form-input">
					<gui-upload-images2 @change="choosePhotoGwpz($event, 'shoppingCert')" :header="header"
						fileName="file" ref="uploadshoppingCert" @uploaded="uploadedGwpz($event, 'shoppingCert')"
						:uploadServerUrl="`${$http.config.baseUrl}/common/upload`"
						:maxFileNumber="1"></gui-upload-images2>
				</view>
			</view>
			<view class="data-form-item flex-ac">
				<text class="data-form-label f30">产品合格证</text>
				<view class="data-form-input">
					<gui-upload-images2 @change="choosePhotoGwpz($event, 'qualityCert')" :header="header"
						fileName="file" ref="uploadqualityCert" @uploaded="uploadedGwpz($event, 'qualityCert')"
						:uploadServerUrl="`${$http.config.baseUrl}/common/upload`"
						:maxFileNumber="1"></gui-upload-images2>
				</view>
			</view>
			<view class="data-form-item flex-ac">
				<text class="data-form-label f30">报关单文件(进口必填)</text>
				<view class="data-form-input">
					<gui-upload-images2 @change="choosePhotoGwpz($event, 'billEntry')" :header="header" fileName="file"
						ref="uploadbillEntry" @uploaded="uploadedGwpz($event, 'billEntry')"
						:uploadServerUrl="`${$http.config.baseUrl}/common/upload`"
						:maxFileNumber="1"></gui-upload-images2>
				</view>
			</view>
			<view class="data-form-item flex-ac">
				<text class="data-form-label f30">检疫合格证明文件(禽类肉类必填)</text>
				<view class="data-form-input">
					<gui-upload-images2 @change="choosePhotoGwpz($event, 'jyQualityCert')" :header="header"
						fileName="file" ref="uploadjyQualityCert" @uploaded="uploadedGwpz($event, 'jyQualityCert')"
						:uploadServerUrl="`${$http.config.baseUrl}/common/upload`"
						:maxFileNumber="1"></gui-upload-images2>
				</view>
			</view>
			<view class="data-form-item flex-ac">
				<text class="data-form-label f30">猪瘟病毒检测阴性报告文件(采购猪肉必填)</text>
				<view class="data-form-input">
					<gui-upload-images2 @change="choosePhotoGwpz($event, 'vCheckCert')" :header="header" fileName="file"
						ref="uploadvCheckCert" @uploaded="uploadedGwpz($event, 'vCheckCert')"
						:uploadServerUrl="`${$http.config.baseUrl}/common/upload`"
						:maxFileNumber="1"></gui-upload-images2>
				</view>
			</view>
			<view class="data-form-item flex-ac">
				<text class="data-form-label f30">肉品品质检验合格证明文件(采购猪肉必填)</text>
				<view class="data-form-input">
					<gui-upload-images2 @change="choosePhotoGwpz($event, 'rpQualityCert')" :header="header"
						fileName="file" ref="uploadrpQualityCert" @uploaded="uploadedGwpz($event, 'rpQualityCert')"
						:uploadServerUrl="`${$http.config.baseUrl}/common/upload`"
						:maxFileNumber="1"></gui-upload-images2>
				</view>
			</view>
			<view class="data-form-item flex-ac" v-for="(item,index) in uploadSet.fileList" :key="index">
				<text class="data-form-label f30">{{item.name}}</text>
				<view class="data-form-input">
					<gui-upload-images2 @change="choosePhoto($event, index)" :header="header" fileName="file"
						:ref="'uploadimgcom'+index" @uploaded="uploaded($event, index)"
						:uploadServerUrl="`${$http.config.baseUrl}/common/upload`"
						:maxFileNumber="1"></gui-upload-images2>
				</view>
			</view>
			<view class="data-form-item flex-ac">
				<text class="data-form-label f30">采购物品</text>
				<view class="data-form-input gui-flex gui-justify-content-end">
					<button type="default" class="gui-button gui-bg-blue gui-noborder" @click="jumpGoods"
						style="width: 180rpx;height: 60rpx;line-height: 60rpx;padding: 0;font-size: 24rpx;">
						<text class="gui-color-white gui-button-text" style="line-height: 60rpx;">商品录入</text>
					</button>
				</view>
			</view>
			<scroll-view scroll-x="true">
				<view class="gui-table gui-border-l gui-border-t" style="margin-top:50rpx;width: 1000rpx;">
					<view class="gui-theader gui-flex gui-rows gui-nowrap gui-bg-gray">
						<text class="gui-td gui-border-r gui-border-b gui-td-text gui-bold gui-text-center">物品名称</text>
						<text class="gui-td gui-border-r gui-border-b gui-td-text gui-bold gui-text-center">数量</text>
						<text class="gui-td gui-border-r gui-border-b gui-td-text gui-bold gui-text-center">单位</text>
						<text class="gui-td gui-border-r gui-border-b gui-td-text gui-bold gui-text-center">生产日期</text>
						<text class="gui-td gui-border-r gui-border-b gui-td-text gui-bold gui-text-center">过期日期</text>
						<text class="gui-td gui-border-r gui-border-b gui-td-text gui-bold gui-text-center">食品类型</text>
						<text class="gui-td gui-border-r gui-border-b gui-td-text gui-bold gui-text-center">子类型</text>
						<text class="gui-td gui-border-r gui-border-b gui-td-text gui-bold gui-text-center">是否进口</text>
						<text class="gui-td gui-border-r gui-border-b gui-td-text gui-bold gui-text-center">操作</text>
					</view>
					<view class="gui-tbody gui-flex gui-rows gui-nowrap" v-for="(item, index) in goodsList"
						:key="index">
						<text class="gui-td gui-td-text gui-text-center gui-border-r gui-border-b">{{item.name}}</text>
						<text
							class="gui-td gui-td-text gui-text-center gui-border-r gui-border-b">{{item.quantity}}</text>
						<text class="gui-td gui-td-text gui-text-center gui-border-r gui-border-b">{{item.unit}}</text>
						<text
							class="gui-td gui-td-text gui-text-center gui-border-r gui-border-b">{{item.produceTime}}</text>
						<text
							class="gui-td gui-td-text gui-text-center gui-border-r gui-border-b">{{item.expireTime}}</text>
						<text
							class="gui-td gui-td-text gui-text-center gui-border-r gui-border-b">{{item.fTypeName}}</text>
						<text
							class="gui-td gui-td-text gui-text-center gui-border-r gui-border-b">{{item.fTypeSubName}}</text>
						<text
							class="gui-td gui-td-text gui-text-center gui-border-r gui-border-b">{{(item.whetherImport == 0) ? '否' : '是'}}</text>
							<text
								class="gui-td gui-td-text gui-text-center gui-border-r gui-border-b" style="color: #dc362e;" @click="delGoods(item, index)">删除</text>
					</view>
				</view>
			</scroll-view>

		</view>
		<view class="right-area-footer2 flex-ac bgfff" v-if="!optionDisabled">
			<view class="saveBtn cancleBtn" @tap="handleCancle">取消</view>
			<view class="saveBtn" @tap="handleSubmit">保存</view>
		</view>
	</view>
</template>

<script>
	export default {
		data() {
			return {
				did: '',
				needPploadedImgs: [],
				dataForm: { //表单
					supplierId: '',
					type: '',
					creditCode: '',
					shoppingCert: '',
					params: {
						products: []
					}
				},
				cpddDateRangeVal: '',
				cpddDateRangeVal2: '',
				selectList: [], //上一页带过来，如果上一页用不到，可以在这里调用赋值
				optionDisabled: false,
				typeList: [{
						name: '生产企业采购',
						val: 'Manufacturer'
					},
					{
						name: '经营单位采购',
						val: 'BusinessUnit'
					},
					{
						name: '食用农产品生产者',
						val: 'FoodProducer'
					},
					{
						name: '屠宰企业',
						val: 'Butcher'
					},
					{
						name: '个体工商户',
						val: 'SelfEmployed'
					}
				],
				foodTypeList: [{
						name: '食品',
						val: 'Food'
					},
					{
						name: '食用农产品',
						val: 'FoodFarm'
					},
					{
						name: '食品添加剂',
						val: 'FoodAdd'
					},
					{
						name: '食品相关',
						val: 'FoodRelate'
					}
				],
				uploadList: [{
					id: 1,
					fileList: [{
						name: '加盖公章的营业执照图片'
					}, {
						name: '食品生产许可证复印件图片'
					}]
				}, {
					id: 2,
					fileList: [{
						name: '加盖公章的营业执照图片'
					}, {
						name: '食品经营许可证复印件图片或备案证明'
					}]
				}, {
					id: 3,
					fileList: [{
						name: '身份证正反面复印件图片'
					}]
				}, {
					id: 4,
					fileList: [{
						name: '供货方盖章或签字的食品生产许可证'
					}, {
						name: '供货方盖章或签字的食品经营许可证'
					}, {
						name: '供货方盖章或签字的营业执照'
					}]
				}, {
					id: 5,
					fileList: [{
						name: '供货方盖章或签字的食品生产许可证'
					}, {
						name: '供货方盖章或签字的食品经营许可证'
					}, {
						name: '供货方盖章或签字的营业执照'
					}]
				}],
				uploadSet: {
					fileList: []
				},
				checkIndex: '',
				checkArr: [],
				header: {
					"Authorization": uni.getStorageSync('lifeData')?.vuex_token
				},
				goodsList: []
			}
		},
		onLoad(options) {
			console.log('options', options);
			this.did = options.id || ''
			this.optionDisabled = options.op == 'look' ? true : false
			let title = options.op == 'look' ? '详情' : options.op == 'add' ? '新增' : '编辑'
			if (options.op != 'add') {
				this.loadDetail();
			}
			uni.$on('selectCgd', (data) => {
				console.log(data);
				this.dataForm.supplierId = data.id;
				this.dataForm.supplierName = data.name;
				this.$forceUpdate()
			})
			uni.setNavigationBarTitle({
				title
			})
			uni.$on('reFGoodsList', (data) => {
				this.goodsList.push(data);
			})
		},
		onUnload() {
			uni.$off('selectCgd')
			uni.$off('reFGoodsList')
		},
		methods: {
			loadDetail() {
				this.$http.get(`/material/purchaseOrder/${this.did}`).then(res => {
					if (res.code == 200) {
						let {
							id,
							supplierId,
							supplierName,
							type,
							creditCode,
							shoppingCert,
							qualityCert,
							billEntry,
							jyQualityCert,
							vCheckCert,
							rpQualityCert,
							params,
							bLicense,
							pLicense,
							fBLicense,
							idCopy
						} = res.data;
						this.dataForm.id = id;
						this.dataForm.supplierId = supplierId;
						this.dataForm.supplierName = supplierName;
						this.dataForm.type = type;
						this.dataForm.creditCode = creditCode;
						this.dataForm.shoppingCert = shoppingCert;
						this.dataForm.qualityCert = qualityCert;
						this.dataForm.billEntry = billEntry;
						this.dataForm.jyQualityCert = jyQualityCert;
						this.dataForm.vCheckCert = vCheckCert;
						this.dataForm.rpQualityCert = rpQualityCert;
						this.dataForm.params = params;
						this.dataForm.bLicense = bLicense;
						this.dataForm.pLicense = pLicense;
						this.dataForm.fBLicense = fBLicense;
						this.dataForm.idCopy = idCopy;
						this.goodsList = params.products.map(e => {
							let fTypeName = this.foodTypeList.filter(item => item.val == e.fType)
							return {
								fTypeSubName: e.params.fTypeSubName,
								fTypeName: fTypeName[0].name,
								...e
							}
						});
						this.$refs.uploadshoppingCert.setItems([shoppingCert]);
						this.$refs.uploadqualityCert.setItems([qualityCert]);
						this.$refs.uploadbillEntry.setItems([billEntry]);
						this.$refs.uploadjyQualityCert.setItems([jyQualityCert]);
						this.$refs.uploadvCheckCert.setItems([vCheckCert]);
						this.$refs.uploadrpQualityCert.setItems([rpQualityCert]);
						this.typeChangeEdit(type)
					}
				})
			},
			openSelect() {
				this.$u.to(`/pages/gysda/ylgysgl-warp/index?type=select`)
			},
			jumpGoods() {
				this.$u.to(`/pages/ylgl/cgd-warp/goodsForm?op=add`)
			},
			typeChange(e) {
				this.typeList.some((item, index) => {
					if (item.val == e) {
						this.checkIndex = index;
						this.needPploadedImgs = [];
						let filelist = this.uploadList[index].fileList;
						filelist.forEach(e => {
							this.needPploadedImgs.push([])
						})
						this.uploadSet = this.uploadList[index];
						return true;
					}
				})
				this.$forceUpdate();
				console.log(this.uploadSet);
			},
			delGoods(item, index) {
				if(item.id) {// 编辑需要调用接口
					this.$http.delete(`/material/purchaseOrderProduct/${item.id}`).then(res => {
						if (res.code == 200) {
							this.goodsList.splice(index, 1)
						}
					})
				}else {
					this.goodsList.splice(index, 1)
				}
			},
			typeChangeEdit(e) {
				this.typeList.some((item, index) => {
					if (item.val == e) {
						this.checkIndex = index;
						this.needPploadedImgs = [];
						let filelist = this.uploadList[index].fileList;
						filelist.forEach(e => {
							this.needPploadedImgs.push([])
						})
						this.uploadSet = this.uploadList[index];
						return true;
					}
				})
				this.$forceUpdate();
				setTimeout(() => {
					if (this.checkIndex == 0) { // 生产企业
						this.$refs['uploadimgcom0'][0].setItems([this.dataForm.bLicense]);
						this.$refs['uploadimgcom1'][0].setItems([this.dataForm.pLicense]);
					}
					if (this.checkIndex == 1) { // 经营单位
						this.$refs['uploadimgcom0'][0].setItems([this.dataForm.bLicense]);
						this.$refs['uploadimgcom1'][0].setItems([this.dataForm.fBLicense]);
					}
					if (this.checkIndex == 2) { // 食用农产品
						this.$refs['uploadimgcom0'][0].setItems([this.dataForm.idCopy]);
					}
					if (this.checkIndex == 3) { // 生产企业
						this.$refs['uploadimgcom0'][0].setItems([this.dataForm.pLicense]);
						this.$refs['uploadimgcom1'][0].setItems([this.dataForm.fBLicense]);
						this.$refs['uploadimgcom2'][0].setItems([this.dataForm.bLicense]);
					}
					if (this.checkIndex == 4) { // 生产企业
						this.$refs['uploadimgcom0'][0].setItems([this.dataForm.pLicense]);
						this.$refs['uploadimgcom1'][0].setItems([this.dataForm.fBLicense]);
						this.$refs['uploadimgcom2'][0].setItems([this.dataForm.bLicense]);
					}
				}, 200)
				console.log(this.uploadSet);
			},
			handleCancle() {
				this.$u.back()
			},
			handleSubmit() {
				if (!this.dataForm.supplierId) return this.$u.msg('请选择供应商')
				if (!this.dataForm.type) return this.$u.msg('请选择采购类型')
				if (!this.dataForm.creditCode) return this.$u.msg('请输入社会信用代码')
				if (!this.dataForm.shoppingCert) return this.$u.msg('请上传购物凭证文件')
				this.checkArr = [];
				if (this.needPploadedImgs.length <= 0) {
					return;
				}
				this.needPploadedImgs.forEach((item, index) => {
					this.$refs['uploadimgcom' + index][0].upload();
				})

				// uni.$emit('reFlashList')
				// this.$u.msg('已新增')
				// this.$u.back(1, 1000)
			},
			choosePhotoGwpz(e, name) {
				console.log('upload' + name);
				this.$refs['upload' + name].upload();
			},
			uploadedGwpz(uploadedImgs, name) {
				let arr = []
				for (var i = 0; i < uploadedImgs.length; i++) {
					arr.push(uploadedImgs[i].url)
				}
				this.dataForm[name] = arr.join();
			},
			choosePhoto(e, index) { //选择图片
				this.needPploadedImgs[index] = e;
			}, // 图片上传完毕执行 uploaded 函数
			uploaded: function(uploadedImgs, index) {
				console.log('图片上传完毕，开始提交数据');
				// 组合数据给后端 api 提交
				console.log(uploadedImgs);
				let arr = []
				for (var i = 0; i < uploadedImgs.length; i++) {
					arr.push(uploadedImgs[i].url)
				}
				this.checkArr.push(1)
				this.uploadList[this.checkIndex].fileList[index].src = arr.join();
				if (this.checkArr.length == this.needPploadedImgs.length) { // 上传完了
					console.log("该提交了");
					console.log(this.uploadList);
					this.realSumbit();
				}
			},
			realSumbit() {
				let uploadLen = this.uploadList[this.checkIndex].fileList.length;
				let srcList = this.uploadList[this.checkIndex].fileList.map((e) => e.src);
				if (srcList.length < uploadLen) return this.$u.msg('文件上传不完整，请检查')
				if (this.checkIndex == 0) { // 生产企业
					this.dataForm.bLicense = srcList[0]
					this.dataForm.pLicense = srcList[1]
				}
				if (this.checkIndex == 1) { // 经营单位
					this.dataForm.bLicense = srcList[0]
					this.dataForm.fBLicense = srcList[1]
				}
				if (this.checkIndex == 2) { // 食用农产品
					this.dataForm.idCopy = srcList[0]
				}
				if (this.checkIndex == 3) { // 生产企业
					this.dataForm.pLicense = srcList[0]
					this.dataForm.fBLicense = srcList[1]
					this.dataForm.bLicense = srcList[2]
				}
				if (this.checkIndex == 4) { // 生产企业
					this.dataForm.pLicense = srcList[0]
					this.dataForm.fBLicense = srcList[1]
					this.dataForm.bLicense = srcList[2]
				}
				this.dataForm.params.products = this.goodsList;
				console.log(this.dataForm.params);
				if (this.dataForm.id) {
					this.$http.put('/material/purchaseOrder', this.dataForm).then(res => {
						if (res.code == 200) {
							uni.$emit('reFlashList')
							this.$u.msg('修改成功')
							this.$u.back(1, 1000)
						}
					})
				} else {
					this.$http.post('/material/purchaseOrder', this.dataForm).then(res => {
						if (res.code == 200) {
							uni.$emit('reFlashList')
							this.$u.msg('已新增')
							this.$u.back(1, 1000)
						}
					})
				}
			}

		}
	}
</script>

<style lang="scss">
	/* 普通表格 */
	.gui-td {
		width: 100rpx;
		flex: 1;
		overflow: hidden;
		padding: 20rpx 10rpx;
		display: flexbox;
	}

	.gui-td-text {
		line-height: 60rpx !important;
		font-size: 24rpx;
	}
</style>